/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.mvc.plugin;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

/**
 * @author zhg2yqq, 2022年12月4日
 * @version zhg2yqq v1.0
 */
@Component
public class AuditMetaObjectHandler implements MetaObjectHandler {
    private Logger log = LoggerFactory.getLogger(AuditMetaObjectHandler.class);
    @Autowired(required = false)
    private ICurrentInfoHolder currentInfoHolder;

    @Override
    public void insertFill(MetaObject metaObject) {
        if (currentInfoHolder == null) {
            log.warn("没有实现注入ICurrentInfoHolder接口，将使用默认system填充createdBy字段");
        }
        this.strictInsertFill(metaObject, "createdBy", () -> {
            if (currentInfoHolder != null) {
                return currentInfoHolder.getAccountName() == null ? "unkown"
                        : currentInfoHolder.getAccountName();
            }
            return "system";
        }, String.class);

        this.strictInsertFill(metaObject, "createdTime", Date::new, Date.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedBy", () -> {
            if (currentInfoHolder != null) {
                return currentInfoHolder.getAccountName() == null ? "unkown"
                        : currentInfoHolder.getAccountName();
            }
            return "system";
        }, String.class);

        this.strictUpdateFill(metaObject, "updatedTime", Date::new, Date.class);
    }

}
